﻿
Imports osi.root.formation
Imports osi.root.procedure
Imports osi.root.utils

Public Class tcp_responder
    Public Shared ReadOnly [default] As tcp_responder
    Private ReadOnly dispatcher As dispatcher

    Shared Sub New()
        [default] = New tcp_responder(commander.dispatcher.default)
    End Sub

    Public Sub New(ByVal dispatcher As dispatcher)
        assert(Not dispatcher Is Nothing)
        Me.dispatcher = dispatcher
    End Sub

    Public Function handler(ByVal i() As Byte, ByVal o As pointer(Of Byte())) As event_comb
        Dim ic As command = Nothing
        Dim oc As command = Nothing
        Dim ec As event_comb = Nothing
        Return New event_comb(Function() As Boolean
                                  ic = New command()
                                  If Not ic.from_bytes(i) Then
                                      Return False
                                  Else
                                      oc = New command()
                                      ec = dispatcher.dispatch(ic, oc)
                                      Return waitfor(ec) AndAlso
                                             goto_next()
                                  End If
                              End Function,
                              Function() As Boolean
                                  Return ec.end_result() AndAlso
                                         eva(o, oc.to_bytes()) AndAlso
                                         goto_end()
                              End Function)
    End Function
End Class
